<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue';
import { getYunDuoToken } from '@/apis/index';

const url = ref<string>(null)
onLoad(({data})=>{
	const temp = JSON.parse(decodeURIComponent(data))
	if (temp.url) url.value = temp.url
	else yunDuoBook(temp.id)
})
 
const yunDuoBook = async (id) =>{
	const userId = wx.getStorageSync('userId') || ''
	if (!userId || userId === ''){
		uni.showModal({
			content:"哎呀，出了点意外情况，需要您重新登录!",
			showCancel:false,
			success(res){
				if (res.confirm){
					uni.clearStorage()
					uni.navigateTo({
						url: '/pages/login/index'
					})
				}
			} 
		})
		return
	}
	console.log(userId)
	const token = await getToken()
	console.log(token, userId, id)
	const buyLink = `https://yicaishi.com/middleware.html?id=${id}`
	const webUrl = `https://yunduo.edu-aliyun.com/app/page-content?id=${id}&ccOutUserId=${userId}&login=true&ccAppToken=${token}&buylink=${encodeURIComponent(buyLink)}`
	url.value = webUrl
	// await feedbackApi({feedbackContent: webUrl})
}
const getStorageSync = (key) => {
  if (storageIsExpired(key)) {
    uni.removeStorageSync(key)
    return null;
  } else {
    const item = uni.getStorageSync(key)
    return JSON.parse(item).value;
  }
}
const storageIsExpired = (key) =>{
  const item = uni.getStorageSync(key)
  if (!item) return true; // 如果没有该key则认为已过期  
  const parsedItem = JSON.parse(item);
  const now = new Date().getTime();
  return now > parsedItem.expiresAt;
}
const setStorageSync = (key, value, minutesToExpire) => {
  const now = new Date().getTime();
  const expiration = now + (minutesToExpire * 60 * 1000);
  uni.setStorageSync(key, JSON.stringify({ value: value, expiresAt: expiration }));
}

const getToken =  async () =>{
	const token = getStorageSync('bookToken')
	if (token){
		console.log('token没有过期')
		return token
	}else{
		console.log('token过期了')
		const { obj } = await getYunDuoToken()
		setStorageSync('bookToken', obj, 50)
		return obj	
	}
}
</script>

<template>
	<web-view :src="url"/>
</template>

<style>
</style>